
package com.fatcat.easybuy.controller;

import com.fatcat.easybuy.annotaion.CheckPermission;
import com.fatcat.easybuy.exception.LoginException;
import com.fatcat.easybuy.pojo.EasyBuyUser;
import com.fatcat.easybuy.service.EasyBuyUserService;
import com.fatcat.easybuy.util.JwtUtil;
import com.fatcat.easybuy.util.ResponseResult;
import com.fatcat.easybuy.util.Sm3Util;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class EasyBuyUserController {

    @Autowired
    private EasyBuyUserService easyBuyUserService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @ApiOperation("登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "登录名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @PostMapping("/login")
    public ResponseResult login(
            @RequestBody Map<String, String> params) {
        String loginName = params.get("loginName");
        String password = params.get("password");
        //查询用户
        EasyBuyUser easyBuyUser = easyBuyUserService.getUserByLoginName(loginName);
        if (easyBuyUser == null) {
            return ResponseResult.error("401", "用户不存在");
        }
        //密码校验
        String encrypt = Sm3Util.hmacEncrypt(password);
        if (!encrypt.equals(easyBuyUser.getPassword())) {
            return ResponseResult.error("401", "密码错误");
        }
        //设置Jwt
        String token = JwtUtil.createToken(easyBuyUser.getId());
        stringRedisTemplate.opsForValue().set(easyBuyUser.getId().toString(), token, 30, TimeUnit.MINUTES);
        //登录成功
        return ResponseResult.success("登录成功")
                .add("token", token)
                .add("userName", easyBuyUser.getUserName())
                .add("type", easyBuyUser.getType());
    }

    //注册
    @ApiOperation("注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "登录名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true),
            @ApiImplicitParam(name = "email", value = "邮箱", required = true),
            @ApiImplicitParam(name = "captcha", value = "验证码", required = true)
    })
    @PostMapping("/register")
    public ResponseResult register(
            @Validated @RequestBody EasyBuyUser easyBuyUser,
            @RequestParam("captcha") String captcha) {
        //查询用户
        EasyBuyUser checkUser = easyBuyUserService.getUserByLoginName(easyBuyUser.getLoginName());
        if (checkUser != null) {
            return ResponseResult.error("用户已存在");
        }
        //验证码校验
        if (captcha == null || captcha.isEmpty()) {
            return ResponseResult.error("验证码不能为空");
        }
        String captchaKey = easyBuyUser.getEmail();
        String captchaValue = (String) redisTemplate.opsForValue().get(captchaKey);
        if (captchaValue == null) {
            return ResponseResult.error("验证码过期");
        }
        if (!captchaValue.equals(captcha)) {
            return ResponseResult.error("验证码错误");
        }
        //注册
        String password111 = Sm3Util.hmacEncrypt(easyBuyUser.getPassword());
        easyBuyUser.setPassword(password111);
        if (easyBuyUserService.addUser(easyBuyUser)) {
            //删除验证码
            redisTemplate.delete(captchaKey);
            return ResponseResult.success("注册成功");
        }
        return ResponseResult.error("注册失败");
    }

    //查询所有用户
    @ApiOperation("查询所有用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = true)
    })
    @CheckPermission("0")
    @GetMapping("/getAllUser")
    public ResponseResult getAllUser(@RequestParam Map<String, Object> params) {
        System.out.println("接收的参数：" + params); // 检查是否包含userName
        PageInfo<EasyBuyUser> pageInfo = easyBuyUserService.getAllUser(params);
        if (pageInfo == null) {
            return ResponseResult.error("获取用户分页信息失败");
        }
        if (pageInfo.getList().isEmpty()) {
            return ResponseResult.success("用户列表为空");
        }
        return ResponseResult.success("获取用户分页信息成功").add("pageInfo", pageInfo);
    }

    //根据id查询用户
    @ApiOperation("根据id查询用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    @CheckPermission({"0", "1"})
    @GetMapping("/getUserById/{id}")
    public ResponseResult getUserById(@PathVariable("id") Long id) {
        if (id == null) {
            return ResponseResult.error("id不能为空");
        }
        //查询
        EasyBuyUser easyBuyUser = easyBuyUserService.getUserById(id);
        if (easyBuyUser == null) {
            throw new LoginException("401", "用户不存在");
        }
        return ResponseResult.success("查询成功").add("easyBuyUser", easyBuyUser);
    }


    @ApiOperation("根据id查询用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    @CheckPermission({"0", "1"})
    @GetMapping("/getCurrentUser")
    public ResponseResult  getCurrentUser(@RequestAttribute("userId") Long userId) {

        //查询
        EasyBuyUser easyBuyUser = easyBuyUserService.getUserById(userId);
        if (easyBuyUser == null) {
            throw new LoginException("401", "用户不存在");
        }
        return ResponseResult.success("查询成功").add("easyBuyUser", easyBuyUser);
    }


    //删除用户
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    @CheckPermission("0")
    @DeleteMapping("/deleteUser/{id}")
    public ResponseResult deleteUser(@PathVariable("id") Long id) {
        if (id == null) {
            return ResponseResult.error("id不能为空");
        }
        //删除
        if (easyBuyUserService.deleteUser(id)) {
            return ResponseResult.success("删除成功");
        }
        return ResponseResult.error("删除失败");
    }

    //更新用户
    @ApiOperation("更新用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    @CheckPermission({"0", "1"})
    @PostMapping("/updateUser")
    public ResponseResult updateUser(@RequestBody EasyBuyUser easyBuyUser) {
        //更新
        if (easyBuyUserService.updateUser(easyBuyUser)) {
            return ResponseResult.success("更新成功");
        }
        return ResponseResult.error("更新失败");
    }

    //检查登录名是否重复
    @ApiOperation("检查登录名是否重复")
    @ApiImplicitParam(name = "loginName", value = "登录名", required = true)
    @GetMapping("/checkLoginName")
    public ResponseResult checkLoginName(@RequestParam("loginName") String loginName) {
        if (loginName == null || loginName.isEmpty()) {
            return ResponseResult.error("登录名不能为空");
        }
        //检查登录名是否重复
        EasyBuyUser easyBuyUser = easyBuyUserService.getUserByLoginName(loginName);
        if (easyBuyUser == null) {
            return ResponseResult.success("登录名可用");
        }
        return ResponseResult.error("登录名已存在");
    }

    //        //测试密码
//    @GetMapping("/testPassword")
//    public ResponseResult testPassword(@RequestParam("password") String password) {
//        String encryptPassword = Sm3Util.hmacEncrypt(password);
//        return ResponseResult.success("加密后的密码为：" + encryptPassword);
//    }
    //修改密码
    @ApiOperation("修改密码")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    @CheckPermission({"0", "1"})
    @PostMapping("/updatePassword")
    public ResponseResult updatePassword(
            @RequestParam("id") Long id,
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword) {
        //查询用户
        EasyBuyUser easyBuyUser = easyBuyUserService.getUserById(id);
        if (easyBuyUser == null) {
            throw new LoginException("401", "用户不存在");
        }
        //验空
        if (oldPassword == null || oldPassword.isEmpty() || newPassword == null || newPassword.isEmpty()) {
            return ResponseResult.error("密码不能为空");
        }
        //比较密码
        String oldPasswordSm3 = Sm3Util.hmacEncrypt(oldPassword);
        //比较密码
        if (!oldPasswordSm3.equals(easyBuyUser.getPassword())) {
            return ResponseResult.error("旧密码错误");
        }
        //加密新密码
        String newPasswordSm3 = Sm3Util.hmacEncrypt(newPassword);
        easyBuyUser.setPassword(newPasswordSm3);
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("password", newPasswordSm3);
        //更新
        if (easyBuyUserService.updatePassword(params)) {
            return ResponseResult.success("密码更新成功");
        }
        return ResponseResult.error("密码更新失败");
    }

    //修改邮箱
    @ApiOperation("修改邮箱")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    @PostMapping("/updateEmail")
    @CheckPermission({"0", "1"})
    public ResponseResult updateEmail(
            @RequestParam("id") Long id,
            @RequestParam("email") String email,
            @RequestParam("captcha") String captcha) {
        //验空
        if (id == null || email == null || email.isEmpty() || captcha == null || captcha.isEmpty()) {
            return ResponseResult.error("参数不能为空");
        }
        //校验邮箱格式
        if (!email.matches("^[a-zA-Z0-9_.]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$")) {
            return ResponseResult.error("邮箱格式错误");
        }
        if (easyBuyUserService.getUserByEmail(email) != null) {
            return ResponseResult.error("邮箱已存在");
        }
        //查询用户
        EasyBuyUser easyBuyUser = easyBuyUserService.getUserById(id);
        if (easyBuyUser == null) {
            throw new LoginException("401", "用户不存在");
        }
        //验证码校验
        String captchaValue = (String) redisTemplate.opsForValue().get(email);
        if (captchaValue == null) {
            return ResponseResult.error("验证码过期");
        }
        if (!captchaValue.equals(captcha)) {
            return ResponseResult.error("验证码错误");
        }
        //删除验证码
        if (!redisTemplate.delete(email)) {
            return ResponseResult.error("验证码删除失败");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("email", email);
        //更新
        if (easyBuyUserService.updateEmail(params)) {
            return ResponseResult.success("邮箱更新成功");
        }
        return ResponseResult.error("邮箱更新失败");
    }

    //退出当前账号
    @ApiOperation("退出当前账号")
    @CheckPermission({"0", "1"})
    @GetMapping("/logout")
    public ResponseResult logout(@RequestAttribute("userId") Long userId) {
        //删除token
        if (!stringRedisTemplate.delete(userId.toString())) {
            return ResponseResult.error("退出失败");
        }
        return ResponseResult.success("退出成功");
    }
}

